<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="注意：只允许为第三分类设置相关参数！" type="warning" :closable="false"></el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader v-model="selectedKeys" :options="cateList"
                        :props="{ expandTrigger: 'hover', checkStrictly: 'true', ...cascaderProps }"
                        @change="cateChanged" clearable style="width: 30%;"></el-cascader>
                </el-col>
            </el-row>
            <!-- tab 页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <!-- 添加面板 -->
                <el-tab-pane :label="item.label" :name="item.name" v-for="(item, i) in tabObject" :key="i">
                    <el-button :type="item.type" :disabled="isBtnDisabled" @click="addOpe">{{ item.btn }}</el-button>
                    <el-table :data="tableData" :border="true" stripe v-show="tableData && tableData.length > 0">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                                    @close="handleClose(i, scope.row)">{{ item }}</el-tag>
                                <!-- 动态tag标签 -->
                                <el-input class="input-btn-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New
                                    Tag</el-button>
                            </template>

                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit"
                                    @click="editOpe(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete"
                                    @click="delOpe(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <!-- 添加/编辑参数对话框 -->
            <el-dialog :title="'添加' + titleText" :visible.sync="dialogVisible" width="50%">
                <el-form :model="form" :rules="formRules" ref="formRef" label-with="100px">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input type="text" v-model="form.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 按钮区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submit(opeFlag)">确定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
export default {
    created() {
        this.initTabObj()
        this.getCateList()
    },
    data() {
        return {
            cateList: [], // 商品分类列表
            // 级联选择器的配置对象
            cascaderProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            tabObject: [], // 保存tabpane对象数组
            tableData: [],
            selectedKeys: [], // 级联双向绑定的数组
            activeName: 'many', // 激活页签双向绑定的数据
            dialogVisible: false,
            form: { // 表单数据对象
                attr_name: ''
            },
            formRules: {
                attr_name: { required: true, message: '请输入名称', trigger: 'blur' }
            },
            opeFlag: '', // 指定操作类型：1：添加；2：编辑
            inputVisible: false, // 控制文本输入框和按钮的切换显示
            inputValue: '', // 双向绑定输入框的内容
        };
    },
    computed: {
        isBtnDisabled() { // 用来控制'添加xx'的按钮是否置灰
            if (this.selectedKeys.length !== 3)
                return true
            return false
        },
        // 当前选中的三级分类的ID
        cateId() {
            return this.selectedKeys.length === 3 ? this.selectedKeys[2] : null
        },
        titleText() { // 控制对话框的标题
            if (this.activeName === 'many')
                return '动态参数'
            return '静态属性'
        },
    },
    methods: {
        initTabObj() { // 初始化tabPane对象数组
            this.tabObject = []
            this.tabObject.push({ label: '动态参数', name: 'many', type: 'primary', btn: '添加参数' })
            this.tabObject.push({ label: '静态属性', name: 'only', type: 'primary', btn: '添加属性' })
        },
        async getCateList() { // 获取商品分类列表
            const res = await this.$http.get('categories')
            if (res.meta.status != 200)
                return this.$message.error('商品分类数据列表获取失败')
            this.cateList = JSON.parse(JSON.stringify(res.data))
            this.$message.success('商品分类列表数据获取成功')
        },
        async cateChanged() { // 监听选择框选项变化事件
            // 若选中项不是三级分类
            if (this.selectedKeys.length != 3) {
                this.tableData = [] // clearble清空选项时，需置空表格数据
                this.selectedKeys = []
                return
            }

            // 选中项是三级分类
            const res = await this.$http.get(`categories/${this.cateId}/attributes`,
                { params: { sel: this.activeName } })
            if (res.meta.status !== 200) {
                return this.$message.error('获取参数列表失败')
            }
            res.data.forEach(item => { // 将对象的某属性（字符串）变成数组
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                // 控制文本框的显示与否
                item.inputVisible = false
                item.inputValue = ''
            });
            console.log('选中的：', this.selectedKeys);
            this.tableData = res.data
            console.log('表格数据：', this.tableData);
            this.$message.success('获取参数列表成功')
        },
        handleClick() {
            console.log(this.activeName);
            this.cateChanged()
        },
        addOpe() { // 打开添加对话框
            this.opeFlag = '1'
            this.form = {}
            this.dialogVisible = true
        },
        editOpe(row) { // 打开编辑对话框
            this.opeFlag = '2'
            this.form = JSON.parse(JSON.stringify(row))
            this.dialogVisible = true
        },
        async delOpe(row) { // 删除操作
            this.$confirm('是否删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
                if (res.meta.status != 200) return this.$message.error('删除失败')
                this.cateChanged()
                this.$message.success('删除成功')
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消删除' })
            })
        },
        submit(flag) { // 编辑或添加信息，提交表单
            this.$refs.formRef.validate(async valid => {
                if (!valid) return
                if (flag == '1') { // 添加操作
                    const res = await this.$http.post(`categories/${this.cateId}/attributes`,
                        {
                            attr_name: this.form.attr_name,
                            attr_sel: this.activeName
                        })
                    if (res.meta.status != 201) {
                        return this.$message.error('添加失败')
                    }
                    this.$message.success('添加成功')
                } else { // 编辑操作
                    const res = await this.$http.put(`categories/${this.cateId}/attributes/${this.form.attr_id}`,
                        {
                            attr_name: this.form.attr_name,
                            attr_sel: this.activeName
                        })
                    if (res.meta.status != 200) {
                        return this.$message.error('编辑失败')
                    }
                    this.$message.success('编辑成功')
                }
                // this.initTabObj()
                // this.getCateList()
                this.cateChanged()
                this.dialogVisible = false
            })
        },
        closeDialog() { // 监听对话框的关闭事件
            this.$refs['formRef'].resetFields()
        },
        async alertAttr(row) { // 删除或修改参数项调用的公共方法
            const res = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if (res.meta.status != 200) return this.$message.error('修改参数项失败')
            this.$message.success('修改参数项成功')
        },
        handleInputConfirm(row) { // 回车键抬起时或者输入框失去焦点时的触发事件
            if (row.inputValue.trim().length == 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            // 若输入有效字符，另外处理
            row.attr_vals.push(row.inputValue.trim())
            this.alertAttr(row)
            row.inputValue = ''
            row.inputVisible = false
        },
        showInput(row) {
            row.inputVisible = true
            // 文本框自动获得焦点
            // $nextTick方法：当页面上元素被重新渲染出来之后，才会执行回调函数中的代码
            this.$nextTick(() => {
                this.$refs.saveTagInput[0].$refs.input.focus()
            })
        },
        // 删除参数项
        handleClose(index, row) {
            row.attr_vals.splice(index, 1)
            this.alertAttr(row)
        }
    },
};
</script>

<style lang="less" scoped>
.cat_opt {
    margin-top: 10px;
}

.el-tag {
    margin-left: 5px;
}

.input-btn-tag {
    width: 120px
}

.button-new-tag {
    margin-left: 10px;
    text-align: center;
}
</style>